package com.rongji.dfish.ui.helper;

import java.util.ArrayList;
import java.util.List;

import com.rongji.dfish.base.Utils;
import com.rongji.dfish.ui.AbstractWidgetWrapper;
import com.rongji.dfish.ui.FormElement;
import com.rongji.dfish.ui.JsonObject;
import com.rongji.dfish.ui.Layout;
import com.rongji.dfish.ui.Widget;
import com.rongji.dfish.ui.layout.AbstractLayout;
import com.rongji.dfish.ui.layout.ButtonBar;
import com.rongji.dfish.ui.layout.FrameLayout;
import com.rongji.dfish.ui.layout.HorizontalLayout;
import com.rongji.dfish.ui.layout.VerticalLayout;
import com.rongji.dfish.ui.widget.Button;

/**
 * 标签面板
 * FIXME 暂未封装完成
 * @author DFish Team
 *
 */
public class TabPanel extends AbstractWidgetWrapper<TabPanel, VerticalLayout> implements Layout<TabPanel, Widget<?>> ,JsonObject {

	private List<Object[]> subItems = new ArrayList<Object[]>();
	private int focusIndex = -1;
	private String focusWidgetId;
	// 单个tab按钮高度
	private String tabHeight;
	// 单个tab按钮宽度
	private String tabWidth;
	// tab的位置
	private String tabPosition;
	// tab的样式
	private String tabCls;
	
	// FIXME h-按钮水平摆放,v-按钮垂直摆放;角落的名称 nw-西北,ne-东北,sw-西南,se-东南
	/**
	 * 
	 */
	public static final String POS_TOP_LEFT = "h_nw";
	/**
	 * 
	 */
	public static final String POS_TOP_RIGHT = "h_ne";
	/**
	 * 
	 */
	public static final String POS_BOTTOM_LEFT = "h_sw";
	/**
	 * 
	 */
	public static final String POS_BOTTOM_RIGHT = "h_se";
	
	/**
	 * 
	 */
	public static final String POS_LEFT_TOP = "v_nw";
	/**
	 * 
	 */
	public static final String POS_RIGHT_TOP = "v_ne";
	// FIXME 暂未实现
//	public static final String POS_LEFT_BOTTOM = "v_sw";
//	public static final String POS_RIGHT_BOTTOM = "v_se";
	
	/**
	 * 构造函数
	 * @param id
	 */
	public TabPanel(String id) {
		prototype = new VerticalLayout(id);
		setId(id);
	}
	
	@Override
    public TabPanel setId(String id) {
		prototype.setId(id);
	    return super.setId(id);
    }

	@Override
    public VerticalLayout getPrototype(boolean lock) {
    	if (tryRebuild()) {
    		buildPrototype();
    	}
	    return super.getPrototype(lock);
    }
	
	protected void buildPrototype() {
		if (Utils.isEmpty(subItems)) {
			// FIXME 没有任何tab页
		} else {
			
			String tabHeight = Utils.notEmpty(this.tabHeight) ? this.tabHeight : "";
			String tabWidth = Utils.notEmpty(this.tabWidth) ? this.tabWidth : "";
			
			if (Utils.isEmpty(tabPosition)) {
				tabPosition = POS_TOP_LEFT;
			}
			String[] posArray = tabPosition.split("_");
			String pId = prototype.getId();
			AbstractLayout<?, Widget<?>> shell = null;
			FrameLayout film = new FrameLayout(getId() + "_film");
			film.setWidth("*");
			film.setHeight("*");
			String tabStyleClass = Utils.isEmpty(tabCls) ? "f-tab-bar" : tabCls;
			
			ButtonBar tabBar = new ButtonBar(getId() + "_bar").setFocusable(true);
			//"type" : "buttonbar",  "height": 50, "cls": "f-tab-bar z-horz-2", "focusable": true, pub: { "cls": "f-tab" }
			
			boolean tabBarVert = "v".equals(posArray[0]);
			if (tabBarVert) { // 按钮垂直摆放,需水平切割
				shell = new HorizontalLayout("");
				shell.setWidth("*");
				film.setWidth("*");
				tabStyleClass += " z-vert-";
				tabBar.setWidth(tabWidth);
				tabBar.setHeight("*");
			} else { // 按钮水平摆放,需垂直切割
				shell = new VerticalLayout("");
				shell.setHeight("*");
				film.setHeight("*");
				tabStyleClass += " z-horz-";
				tabBar.setWidth("*");
				tabBar.setHeight(tabHeight);
			}
			prototype.add(shell);
			
			if ((tabBarVert && posArray[1].contains("e")) || (!tabBarVert && posArray[1].contains("s"))) {
				shell.add(film);
				shell.add(tabBar);
			} else {
				shell.add(tabBar);
				shell.add(film);
			}
			
			if ("nw".equals(posArray[1])) {
				tabStyleClass += "1";
			} else if ("ne".equals(posArray[1])) {
				tabStyleClass += "2";
			} else if ("se".equals(posArray[1])) {
				tabStyleClass += "3";
			} else if ("sw".equals(posArray[1])) {
				tabStyleClass += "4";
			}
			
//			tabBar.setMaskclz(tabMaskClass);
			tabBar.setCls(tabStyleClass);
			
			Button pub=new Button(null);
			tabBar.setPub(pub);
			pub.setCls("f-tab");
			pub.setName("tab");
			
			if (tabBarVert) {
				pub.setHeight(tabHeight);
				pub.setWidth("100%");
			} else {
				pub.setHeight("100%");
				pub.setWidth(tabWidth);
			}
			
//			HorizontalLayout tabBar = new HorizontalLayout(tabBarName);
//			tabBar.setHeight(tabHeight);
//			tabBar.setAlign(HorizontalLayout.ALIGN_RIGHT);
//			prototype.addNode(tabBar);
//			prototype.addNode(film, "*");
			
			int index = 0;
			boolean hasFocus = false;
			for (Object[] subItem : subItems) {
				Button btn =(Button) subItem[0];
				Widget<?> w = (Widget<?>) subItem[1];
				if (Utils.isEmpty(w.getId())) {
					w.setId(pId + "_" + index);
				}
//				Button btn = new Button((String) subItem[0], (String) subItem[1], "")
				btn.setTarget(w.getId()).setId("btn_" + w.getId());
				tabBar.add(btn);
				
				film.add(w);
				if (!hasFocus) {
					if (Utils.notEmpty(focusWidgetId)) {
						hasFocus = focusWidgetId.equals(w.getId());
						// 这种设置方式失效
						focusIndex = -1;
					} else if (focusIndex >= 0) {
						hasFocus = focusIndex == index;
					} else {
						// 默认第一次就进入这里,第一个聚焦
						hasFocus = true;
					}
					if (hasFocus) {
						btn.setFocus(true);
						film.setDft(w.getId());
						focusIndex = index;
						focusWidgetId = w.getId();
					}
				}
				index++;
			}
		}
	}
	
	/**
	 * 设置默认显示的项
	 * 注意index从0开始。即最 左边/顶部的tab为0
	 * 当与{@link #setFocusWidgetId(String)}一起使用的时候。
	 * 该设置将失效。
	 * @param focusIndex 
	 * @return 本身，这样可以继续设置其他属性
	 */
	public TabPanel setFocusIndex(int focusIndex) {
		if (focusIndex < 0) {
			throw new IndexOutOfBoundsException("focusIndex: " + focusIndex);
		}
		if (focusIndex >= subItems.size()) {
			throw new IndexOutOfBoundsException("focusIndex: " + focusIndex + ", Size: " + subItems.size());
		}
		this.focusIndex = focusIndex;
		return this;
	}
	
	/**
	 * 设置默认显示的组件编号
	 * 
	 * @param widgetId
	 * @return 本身，这样可以继续设置其他属性
	 */
	public TabPanel setFocusWidgetId(String widgetId) {
		this.focusWidgetId = widgetId;
		return this;
	}
	

	/**
	 * @param icon
	 * @param text
	 * @param w
	 * @return 本身，这样可以继续设置其他属性
	 */
	public TabPanel addSubWidget(String icon, String text, Widget<?> w) {
		if (w == null) {
			throw new NullPointerException("The widget is null.");
		}
		subItems.add(new Object[]{ new Button( text).setIcon(icon),  w });
		markRebuild();
		return this;
	}
	
	/**
	 * @param w 元素
	 * @param text 标题
	 * @return 本身，这样可以继续设置其他属性
	 */
	public TabPanel add(Widget<?> w,String text) {
		if (w == null) {
			throw new NullPointerException("The widget is null.");
		}
		subItems.add(new Object[]{ new Button( text), w });
		markRebuild();
		return this;
	}
	/**
	 * @param w 元素
	 * @param b 按钮
	 * @return 本身，这样可以继续设置其他属性
	 */
	public TabPanel add(Widget<?> w,Button b) {
		if (w == null) {
			throw new NullPointerException("The widget is null.");
		}
		subItems.add(new Object[]{ b, w });
		markRebuild();
		return this;
	}
	
	/**
	 * @return 本身，这样可以继续设置其他属性
	 * 
	 */
	public HorizontalLayout getTabLayout() {
		return (HorizontalLayout) prototype.findNodeById(getId() + "_bar");
	}
	
	/**
	 * @return  tabHeight
	 */
	public String getTabHeight() {
		return tabHeight;
	}

	/**
	 * @param tabHeight
	 * @return 本身，这样可以继续设置其他属性
	 * 
	 */
	public TabPanel setTabHeight(String tabHeight) {
		this.tabHeight = tabHeight;
		return this;
	}

	/**
	 * @return tabWidth
	 */
	public String getTabWidth() {
		return tabWidth;
	}

	/**
	 * @param tabWidth
	 * @return 本身，这样可以继续设置其他属性
	 * 
	 */
	public TabPanel setTabWidth(String tabWidth) {
		this.tabWidth = tabWidth;
		return this;
	}

	/**
	 * @return tabPosition
	 */
	public String getTabPosition() {
		return tabPosition;
	}

	/**
	 * @param tabPosition
	 * @return 本身，这样可以继续设置其他属性
	 * 
	 */
	public TabPanel setTabPosition(String tabPosition) {
		this.tabPosition = tabPosition;
		return this;
	}
	/**
	 * 标签页栏的样式
	 * @return String
	 */
	public String getTabCls() {
		return tabCls;
	}
	/**
	 * 标签页栏的样式
	 * @param tabCls String
	 * @return this
	 */
	public TabPanel setTabCls(String tabCls) {
		this.tabCls = tabCls;
		return this;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Widget<?>> findNodes() {
		List<Widget<?>> result=new ArrayList<Widget<?>>(subItems.size());
		for(Object[] row:subItems){
			result.add((Widget<?>) row[1]);
		}
		return result;
	}

	public Widget<?> findNodeById(String id) {
		return super.findNodeById(id);
	}
	
	public List<FormElement<?,?>> findFormElementsByName(String name) {
		return super.findFormElementsByName(name);
	}
	
	public TabPanel removeNodeById(String id) {
		return super.removeNodeById(id);
	}

    public boolean replaceNodeById(Widget<?> w) {
		return super.replaceNodeById(w);
	}

}
